/**
 * @see 办事指南界面
 */
import { timestampToTime } from '../../../utils/util';
let oldShcoolHeadLine = [] // 保存一份原始的校务头条列表
Page({
  data: {
    shcoolHeadLine: [], // 校务头条列表列表
    appMsg: {
      type: '', // 状态
      show: false // 是否展示
    },
    titleValue: '' // 标题
  },
  onLoad () {
    this.setData({ userInfo: wx.getStorageSync('userInfo') })
    this.getWorkList()
  },
  onShow () {
    // this.getWorkList()
  },
  openDetails (e) {
    let { url, index } = e.currentTarget.dataset
    this.data.shcoolHeadLine[index].clicks += 1;
    this.setData({
      shcoolHeadLine: this.data.shcoolHeadLine
    })
    wx.navigateTo({ url })
  },
  /**
   * @see 接口-获取办事指南列表
   */
  getWorkList () {
    let schoolCode = wx.getStorageSync('schoolConfig').schoolCode
    const request = {
      status: 1, // 1是已通过  2是未通过  3是待审核
      schoolCode,  // 学校code
      type: 1,
    }
    this.setData({
      appMsg: {
        type: 'loading',
        show: true
      }
    })
    wx.$API['workService/getShcoolHeadLineList'](request).then((response) => {
      this.setData({
        appMsg: {
          type: 'loading',
          show: false
        }
      })
      const { data } = response
      if (data.length === 0) {
        this.setData({
          appMsg: {
            type: 'none',
            show: true
          }
        })
      } else {
        data.forEach(item => {
          const { content, createTime } = item
          item.timeText = timestampToTime(createTime)
          item.date = item.timeText.split(' ')[0]
          item.time = item.timeText.split(' ')[1]
          let contentText = content.replace(/<[^<>]+>/g, '').replace(/&nbsp;/ig, '')
          if (contentText.length > 20) {
            item.contentText = contentText.substring(0, 20) + '...'
          } else {
            item.contentText = contentText
          }
        })
        oldShcoolHeadLine = JSON.parse(JSON.stringify(data))
        this.setData({
          shcoolHeadLine: data,
        })
      }
    }).catch((error) => {
      console.log(error)
      this.setData({
        appMsg: {
          type: 'err',
          show: true
        }
      })
    })
  },
  /**
   * @see 键盘回车时触发
   */
  search (e) {
    const { value } = e.detail
    let newArr = []
    oldShcoolHeadLine.forEach(headLineInfo => {
      if (headLineInfo.title.indexOf(value) > -1 || headLineInfo.content.indexOf(value) > -1) {
        newArr.push(
          JSON.parse(
            JSON.stringify(headLineInfo)
          )
        )
      }
    })
    if (newArr.length) {
      this.setData({
        shcoolHeadLine: newArr,
        titleValue: value
      })
    } else {
      this.getWorkList()
    }
  },
  /**
   * @see 点击刷新界面
   */
  clickMsgButton () {
    this.getWorkList()
  }
})